import React, {useMemo} from 'react';
import {Button, Space, Table, Modal} from 'antd';
import '../styles/course.scss';
import useCourseListModel from '../view/course/course_model';
import CourseEditor from './courseEditor';
import {eventBus} from '../helpers/eventBus';
import useGlobal from '../hooks/useGlobal';
import useDidMount from '../hooks/useDidMount';

const CourseList = () => {
  const CourseListModel = useCourseListModel();
  const global = useGlobal();

  const courseListColumn = useMemo(() => [
    {
      title: '标题',
      dataIndex: 'title',
      width: 200,
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 100,
      // render: text => global.effect.getCheckInTypeById(text)
      // filters: CheckInModel.state.schoolList
      //   .map(id => ({text: Global.effect.getSchoolById(id)?.name, value: id})),
      // onFilter: (value, record) => record.school_id === value,
    },
    {
      title: '所需积分',
      dataIndex: 'score',
      width: 100,
    },
    {
      title: '积分备注',
      dataIndex: 'memo',
      width: 150,
    },
    {
      title: '上架状态',
      dataIndex: 'status',
      width: 100,
      render: text => text === 0 ? <span style={{color: 'red'}}>已下架</span> : '上架中'
    },
    {
      title: '课程内容',
      dataIndex: 'content',
      render: text => text.length > 50 ? (text.slice(0, 50) + '...') : text
    },
    {
      title: '操作',
      width: 200,
      render: (text, record, index) =>
        <Space size="middle">
          <Button onClick={() => eventBus.emit('editCourse', {record, index})}>修改</Button>
          {record.status === 1 &&
          <>
            <Button onClick={() => {
              Modal.confirm({
                title: '确认下架',
                content: '课程下架不会影响已兑换高校对该课程的资格，请慎重操作下架',
                onOk: () => CourseListModel.effect.removeCourse(record, index)
              });
            }}>下架</Button>
          </>}
        </Space>
    }
  ], []);

  const handleSubmit = async (type, course, index) => {
    // 判断 类型是否为添加
    if (type === 'add') {
      await CourseListModel.effect.addCourse(course);
    } else {
      await CourseListModel.effect.updateCourse(course, index);
    }
  };

  useDidMount(() => {
    if (global.state.courseTypeList.length < 1) {
      global.effect.updateCourseTypeList();
    }
  });

  return (
    <div className='course-list'>
      <div className="add"><Button type="primary" onClick={() => eventBus.emit('newCourse')}>添加课程</Button></div>
      <Table
        className="course-table"
        columns={courseListColumn}
        dataSource={CourseListModel.state.list}
      />
      <CourseEditor
        onSubmit={handleSubmit}
      />
    </div>
  );
};

export default CourseList;